package com.decent.task.config;

import com.decent.common.exception.ErrorCodeException;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * xxl-job日志捕获
 * 如果不开启日志持久化，当任务执行发生异常且未对其进行捕获处理，则会导致异常丢失
 *
 * @className: CustomXxlJobAspect
 * @author: wangyan
 * @date: 2022/3/11
 **/
@Slf4j
@Aspect
@Component
public class CustomXxlJobAspect {
    @Pointcut("@annotation(com.xxl.job.core.handler.annotation.XxlJob)")
    public void xxlJob() {
    }

    @AfterThrowing(pointcut = "xxlJob()", throwing = "e")
    public void xxlJobErrorCatch(JoinPoint joinPoint, Throwable e) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        XxlJob xxlJob = signature.getMethod().getAnnotation(XxlJob.class);
        String taskName = "";
        if (Objects.nonNull(xxlJob)) {
            taskName = xxlJob.value();
        }
        if (e instanceof ErrorCodeException) {
            log.warn("定时任务[{}]执行失败，异常信息：", taskName, e);
        } else {
            log.error("定时任务[{}]执行异常，异常信息：", taskName, e);
        }
        throw e;
    }
}
